<template>
  <div>
    <el-card class="box-card">
      <el-form :inline="true" class="form-container" :model="page.query" ref="queryForm">
        <div class="search">
          <el-form-item label="用户名" prop="username">
            <el-input
              placeholder="请输入用户名"
              prefix-icon="el-icon-search"
              v-model="page.query.username"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName">
            <el-input
              placeholder="请输入真实姓名"
              prefix-icon="el-icon-search"
              v-model="page.query.realName"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input
              placeholder="请输入手机号"
              prefix-icon="el-icon-search"
              v-model.number="page.query.phone"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model.number="page.query.gender" placeholder="请选择性别">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-button icon="el-icon-search" type="success" @click="search">搜索</el-button>
          <el-button icon="el-icon-refresh" type="success" class="reset_btn" @click="reset" >重置</el-button>
        </div>
        <div class="func">
          <el-button icon="el-icon-plus" type="primary" @click="handleAddRole">配置角色</el-button>
          <el-button icon="el-icon-plus" type="primary" @click="handleAdd">添加</el-button>
        </div>
      </el-form>

    </el-card>
    <el-table :data="users"
              highlight-current-row
              @current-change="handleCurrentUser"
              style="width: 100%"
              ref="userTable"
    >

      <el-table-column
        prop="realName"
        label="姓名"
        width="180"
      >
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名"
      >
      </el-table-column>
      <el-table-column
        prop="gender"
        label="性别"
      >
        <template v-slot="scope">
          <span v-if="scope.row.gender===1">男</span>
          <span v-else>女</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱"
      >
      </el-table-column>
      <el-table-column
        prop="phone"
        label="手机号"
      >
      </el-table-column>
      <el-table-column
        prop="deptId"
        label="部门"
      >
      </el-table-column>
      <el-table-column
        prop="createBy"
        label="创建人"
      >
      </el-table-column>
      <el-table-column
        prop="avatar"
        label="头像"
      >
        <template v-slot="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.avatar"
            fit="cover"
          ></el-image>

        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建日期"
        width="180"
      >

      </el-table-column>
      <el-table-column
        label="操作"
        width="180"
      >
        <template v-slot="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(scope.row.id)"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.username)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <page @handlePage="handlePage" :page="page"></page>
    <el-dialog :title="title" :visible.sync="isShow" width="40%">
      <el-form :model="form" inline ref="userForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="form.realName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-show="!form.id">
          <el-input v-model="form.password" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model.number="form.gender" placeholder="请选择性别">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            :headers="{token:$store.state.user.token}"

            class="avatar-uploader"
            :action="action"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="form.avatar" :src="form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="配置角色" :visible.sync="roleShow" width="40%">
      <el-transfer v-model="roleBind.roles"
                   :titles="roleTiles"
                   :data="roles"  style="margin-left: 60px"></el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import settings from '@/settings'
import { deleteUser, editUser, getInfo, getUser, registerUser } from '@/api/user'
import Page from '@/components/page/index.vue'
import { bindRoleRel, getRoleList, getRoles } from '@/api/role'

export default {
  name: 'user',
  data() {
    return {
      roleBind: {
        roles: [],
        userId: '',
      },
      roleTiles: [],
      roles: [],
      roleList: [],
      form: {
        id: '',
        username: '',
        password: '',
        phone: '',
        realName: '',
        email: '',
        gender: 1,
        avatar: ''
      },
      action: settings.avatarUploadUrl,
      title: '',
      isShow: false,
      roleShow: false,
      options: [
        {
          label: '男',
          value: 1
        },
        {
          label: '女',
          value: 2
        }

      ],
      page: {
        current: 1,
        size: 3,
        total: 0,
        query: {
          username: '',
          realName: '',
          phone: '',
          gender: ''
        }
      }
    }
  },
  components: {
    Page
  },
  computed: {
    users() {
      this.page.total = this.$store.state.user.users.total
      return this.$store.state.user.users.records

    }
  },
  methods: {
    handleCurrentUser({ id,realName,username },oldCurrentRow) {
      this.roleTiles=['角色列表',realName]
      this.roleBind.userId = id
    },
    handlePage(flag) {
      this.reloadUser(flag)



    },
    search() {

      this.reloadUser()
    },
    deleteUser(username) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        deleteUser(username).then(()=>{
          this.reloadUser()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    saveRole() {
      bindRoleRel(this.roleBind).then(()=>{
        this.$message({
          type: 'success',
          message: '保存成功!'
        });
        this.roleBind.userId = ''
        this.roleBind.roles = []
        this.roles = []
        this.roleShow = false
        this.$refs.userTable.setCurrentRow();
      })

    },
    handleAddRole() {
      if (!this.roleBind.userId) {
        this.$message.error('请先选择一个用户，再去配置');
        return
      }

      this.roleShow = true
      getRoles().then(data=>{
        this.roles = data.map(n=>{
          return {
            label: n.name,
            key:n.id
          }
        })
      })
      getRoleList(this.roleBind.userId).then(data=>{
        this.roleBind.roles=data.map(n=>n.id)
      })


    },
    handleAdd() {
      this.title = '添加用户'
      this.isShow = true
      this.form.id=''
    },
    handleEdit(id) {
      this.title = '编辑用户'
      this.isShow = true
      getUser(id).then(res => {
        this.form = { ...res }
        this.form.password = ''
        this.form.createTime = ''
        this.form.lastUpdateTime = ''
      })
    },
    handleAvatarSuccess({ data: { path } }) {
      this.form.avatar = path
    },
    resetData() {
      this.$refs.userForm.resetFields()
      this.isShow = false
      this.title = ''
      this.reloadUser()
      this.$store.dispatch('user/getInfo')
    },
    saveOrUpdate() {
      if (this.form.id) {
        editUser(this.form).then(res => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.resetData()
        })

      } else {
        registerUser(this.form).then(res => {
          this.$message({
            type: 'success',
            message: '保存成功!'
          });
          this.resetData()
        })
      }

    },
    cancel() {
      this.roles = []
      this.roleBind.roles=[]
      this.roleShow = false
      this.isShow = false
      this.title = ''
    },

    reloadUser() {
      return new Promise((resolve, reject) => {
        this.$store.dispatch('user/pageUser', this.page).then(() => {
          resolve()
        }).catch((err) => {
          reject(err)

        })
      })

    },

    reset() {
      this.page.current = 1
      this.$refs.queryForm.resetFields()
      this.reloadUser()

    }
  },
  mounted() {
    this.reloadUser()
  }

}
</script>

<style>
.form-container {
  display: flex;
  justify-content: space-between;
}

.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.reset_btn {
  background-color: #722ed1;
  border: 1px solid #722ed1;
}
.reset_btn:hover {
  background-color: #7849b7;
  border: 1px solid #7849b7;
}
.reset_btn:focus {
  background-color: #7849b7;
  border: 1px solid #7849b7;
}
</style>
